package com.cn.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.cn.domain.User;
import com.cn.service.UserService;
import com.cn.service.impl.UserServiceImpl;
import com.cn.utils.MD5Utils;
import com.cn.utils.UserUtils;

public class LoginServlet extends BaseServlet {
	//UserService us = new UserServiceImpl();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try{
//		1、获得参数，并封装到user对象
		User u = new User();
		try {
			BeanUtils.populate(u,request.getParameterMap());
			System.out.println(u.getPassword());
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//      2、检查用户名密码不能为空
		Map<String,String> errors = UserUtils.checkUser(u);
		if(errors.size()>0){
			request.setAttribute("errors", errors);
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
//      3、调用service方法，检查用户名密码是否正确，正确放到session中，作为登陆成功的标识
		u.setPassword(MD5Utils.md5(u.getPassword()));
		User user = us.login(u);
		request.getSession().setAttribute("user", user);
//----------记住用户名逻辑----------------------------------------------------------------
        String remember = request.getParameter("remember");
        Cookie cookie = new Cookie("re",URLEncoder.encode(user.getUsername(), "UTF-8"));
        if("yes".equals(remember)){
            cookie.setMaxAge(60*60*24*14);
        }else{
            cookie.setMaxAge(0);
        }
        response.addCookie(cookie);
//----------记住用户名逻辑-----------------------------------------------------------------
//----------处理自动登录逻辑----------------------------------------------------------------
        String autologin = request.getParameter("autologin");
        Cookie autoCookie = new Cookie("autocookie",user.getUsername()+"@itcast"+user.getPassword());
        if("yes".equals(autologin)){
        	autoCookie.setMaxAge(60*60*24*14);
        }else{
        	autoCookie.setMaxAge(0);
        }
        response.addCookie(autoCookie);
//----------处理自动登录逻辑-----------------------------------------------------------------		
		response.sendRedirect(request.getContextPath()+"/index.jsp");
		}catch(Exception e){
			request.setAttribute("error", e.getMessage());
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
	}

}
